const { pool } = require('../config/database');

// 获取所有活跃公司账户
const getActiveCompanies = async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT id, name, account, bank_name, is_active, created_at, updated_at FROM company_accounts WHERE is_active = TRUE ORDER BY id DESC'
    );
    
    res.json({
      success: true,
      data: rows,
      count: rows.length,
      message: '获取活跃公司数据成功'
    });
  } catch (error) {
    console.error('获取数据错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 获取所有公司账户（包括非活跃）
const getAllCompanies = async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT id, name, account, bank_name, is_active, created_at, updated_at FROM company_accounts ORDER BY id DESC'
    );
    
    res.json({
      success: true,
      data: rows,
      count: rows.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取数据失败',
      error: error.message
    });
  }
};

// 更新公司账户状态
const updateCompanyStatus = async (req, res) => {
  const { id } = req.params;
  const { is_active } = req.body;

  try {
    // 验证参数
    if (typeof is_active !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: 'is_active 必须是布尔值'
      });
    }

    const [result] = await pool.execute(
      'UPDATE company_accounts SET is_active = ? WHERE id = ?',
      [is_active, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到指定的公司账户'
      });
    }

    res.json({
      success: true,
      message: `公司账户状态已${is_active ? '启用' : '停用'}`,
      data: { id, is_active }
    });
  } catch (error) {
    console.error('更新状态错误:', error);
    res.status(500).json({
      success: false,
      message: '更新状态失败',
      error: error.message
    });
  }
};

// 根据ID获取单个公司账户
const getCompanyById = async (req, res) => {
  const { id } = req.params;

  try {
    const [rows] = await pool.execute(
      'SELECT id, name, account, bank_name, is_active, created_at, updated_at FROM company_accounts WHERE id = ?',
      [id]
    );

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到公司账户'
      });
    }

    res.json({
      success: true,
      data: rows[0]
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取数据失败',
      error: error.message
    });
  }
};

module.exports = {
  getActiveCompanies,
  getAllCompanies,
  updateCompanyStatus,
  getCompanyById
};